<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2019/2/20
 * Time: 17:22
 */

namespace app\common\model;


use app\common\lib\Util;
use think\Cache;

/**
 * 用户星盘相关配置模型
 * Class AstroSettingUser
 * @package app\common\model
 */
class AstroSettingUser1751 extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_astro_setting_user';

    const CACHE_KEY = 'astro:setting1:';// . $chart . ':' . $uid . ':' . $tid
    const CACHE_TIME = 86400 * 2;

    /**
     * 获取用户自定义星盘设置
     * @param array $map
     *  tid int 配置方案 1=>现代 2=>古典 3=>特殊
     *  uid int 用户id
     *  chart string 星盘名称 如：now 表示天象盘
     * @return array|bool
     */
    public function getUserSettingByTid($map = [])
    {
        $tid = (int)$map['tid'];
        $uid = (int)$map['uid'];
        $chart = (string)$map['chart'];
        // 初始化
        $setting = false;

        $key = self::CACHE_KEY . $chart . ':' . $uid . ':' . $tid;
        // 从新的缓存获取数据
        if ($this->cache_on >= 1)
        {
            $setting = Cache::get($key);
        }
        // 缓存没有数据
        if ($setting === false)
        {
            $where = ['uid' => $uid, 'tid' => $tid, 'chart' => $chart];
            // 从新的表中获取数据
            try
            {
                $setting = $this->where($where)->value('value');

                if ($setting === null || $setting === 'default')
                {
                    $value = 'default';
                } else
                {
                    $value = json_encode(json_decode($setting, true), true);
                }
                if ($this->cache_on > 0)
                {
                    Cache::set($key, $value, self::CACHE_TIME);
                }
            }
            catch (\Exception $e)
            {
                $setting = false;
            }
        }
        // 查询系统默认星盘配置数据
        $defaultConfig = $this->getDefaultSetting($tid, $chart);

        // 若缓存中存储的数据为 default 字符串，则表示用户使用默认配置.
        if (!$setting || $setting === 'default')
        {
            $setting = $defaultConfig;
        }
        if (!is_array($setting))
        {
            $setting = json_decode($setting, true);
        }

        // 判断是否和默认配置一致
        if ($setting == $defaultConfig)
        {
            $setting['is_default'] = true;
        } else
        {
            $setting['is_default'] = false;
        }

        if (Util::CheckAppVersion('2.9.5') !== '小')
        {
            // 新增相位108
            if (isset($setting['asp_orb_all']) && !isset($setting['asp_orb_all'][108]))
            {
                $setting['asp_orb_all'][108] = 1;
            } elseif (isset($setting['phase']) && !isset($setting['phase'][108]))
            {
                $setting['phase'][108] = [0, 1];
            }
            // 新增相位36
            if (isset($setting['asp_orb_all']) && !isset($setting['asp_orb_all'][36]))
            {
                $setting['asp_orb_all'][36] = 1;
            } elseif (isset($setting['phase']) && !isset($setting['phase'][36]))
            {
                $setting['phase'][36] = [0, 1];
            }
        }

        // 判断数据库是否有新增的字段,若无则获取配置数据
        // 法达星序数据重置
        if ($map['chart'] === 'firdaria' && $setting['firdaria'] === 'default')
        {
            $setting['firdaria'] = $defaultConfig['firdaria'];
        }
        // 界主星数据新增
        if (in_array($map['chart'], ['now', 'natal', 'profection', 'firdaria', 'dodekatemorion', 'trimsamsa', 'zodrel', 'fortune', 'divination']) && !isset($setting['bound_type']))
        {
            $setting['bound_type'] = $defaultConfig['bound_type'];
        }
        // 推运数据增加
        if ($map['chart'] === 'zodrel' && !isset($setting['push_fortune']))
        {
            $setting['push_fortune'] = $defaultConfig['push_fortune'];
        }
        // 希腊点数据增加
        if (in_array($map['chart'], ['now', 'natal', 'profection', 'firdaria', 'dodekatemorion', 'trimsamsa', 'zodrel', 'fortune', 'transits', 'divination', 'synastry']) && !isset($setting['arabic']))
        {
            $setting['arabic'] = $defaultConfig['arabic'];
        }
        // 十度主星数据新增
        if (!isset($setting['decanates']) && in_array($map['chart'], ['now', 'natal', 'profection', 'firdaria', 'dodekatemorion', 'trimsamsa', 'zodrel', 'fortune', 'divination']))
        {
            $setting['decanates'] = $defaultConfig['decanates'];
        }
        // 小限推运方向数据新增
        if ($map['chart'] === 'profection' && !isset($setting['profection_push_direction']))
        {
            $setting['profection_push_direction'] = $defaultConfig['profection_push_direction'];
        }
        // 返照盘新增返照地点选择参数
        if (!isset($setting['location_use']) && in_array($map['chart'], ['solar_return', 'solar_returnvsnatal', 'lunar_return', 'lunar_returnvsnatal'], true))
        {
            $setting['location_use'] = $defaultConfig['location_use'] ?? 0;
        }
        return $setting;
    }

    /**
     * 更新用户星盘配置
     * @param array $map
     * @return AstroSettingUser|bool
     */
    public function updateUserSetting($map = [])
    {
        try
        {
            // 将客户端传来的数据重新json格式化，保证入库格式统一
            $value = json_encode(json_decode($map['chart_value'], true), true);

            $where = [
                'uid' => (int)($map['uid']),
                'tid' => (int)($map['tid']),
                'chart' => $map['chart'],
            ];
            // 更新数据库数据
            $result = $this->where($where)->update(['value' => $value, 'update_time' => time()]);

            if ($result === 0)
            {
                //星盘重置
                $result = $this->insert(['value' => $value, 'create_time' => time(), 'tid' => $map['tid'], 'uid' => $map['uid'], 'chart' => $map['chart']]);
            }

            // 更新完成 更新缓存
            if ($result && $this->cache_on >= 1)
            {
                Cache::set(self::CACHE_KEY . $map['chart'] . ':' . $map['uid'] . ':' . $map['tid'], $value, self::CACHE_TIME);
            }
            $result = true;
        }
        catch (\Exception $e)
        {
            \think\Log::write($e->getMessage(), 'log', true);
            $result = false;
        }

        return $result;
    }

    /**
     * 星盘配置还原
     * @param array $map
     * @param string $value
     * @return bool
     */
    public function restoreUserSetting($map = [], $value = 'default')
    {
        try
        {
            $where = ['uid' => (int)($map['uid']), 'tid' => (int)($map['tid']), 'chart' => (string)$map['chart']];

            $this->where($where)->update(['value' => $value]);
            // 更新完成 更新缓存
            if ($this->cache_on >= 1)
            {
                Cache::set(self::CACHE_KEY . $map['chart'] . ':' . $map['uid'] . ':' . $map['tid'], $value, self::CACHE_TIME);
            }
        }
        catch (\Exception $e)
        {
            $this->error = $e->getMessage();

            return false;
        }
        return true;
    }

    /**
     * 获取后台设置的默认星盘配置 (生成配置文件在runtime下)
     * uid = 0
     * @param int $tid
     * @param string $chart
     * @return mixed
     */
    protected function getDefaultSetting(int $tid = 1, string $chart = 'now')
    {
        $data = false;

        $dir = RUNTIME_PATH . 'setting';

        $filename = $chart . '_' . $tid . '.json';

        try
        {
            // 从生成的配置文件中读取配置
            file_exists($dir . DS . $filename) && $data = file_get_contents($dir . DS . $filename);
        }
        catch (\Exception $e)
        {
            $data = false;
            $this->error = $e->getMessage();
        }

        if ($data === false)
        {
            // 从数据库获取默认配置
            $data = $this->where(['uid' => 0, 'tid' => $tid, 'chart' => $chart])->value('value');

            if ($data)
            {
                // 生成配置文件
                Util::createFile($filename, $data, 'setting');
            }
        }
        return json_decode($data, true);
    }
}
